import janis_core.operators.operator as gen
import janis_core.operators.standard as std
import janis_core.operators.logical as lgc

from constants import PROJECT_ROOT_DIR

sections = [
    ("Regular operators", gen),
    ("Logical operators", lgc),
    ("Standard library", std),
]


# DON'T CHANGE ANYTHING BELOW THIS LINE TO INCLUDE NEW OPERATORS

from inspect import isabstract, isclass
from janis_core import Logger
from janis_core.operators import Operator

docs_dir = PROJECT_ROOT_DIR + "/docs/"
listoperators_path = docs_dir + "references/listoperators.rst"


def prepare_operators():

    ignore = {"StringFormatter"}

    prepared_sections = []
    section_titles = []

    for title, module in sections:
        section_titles.append(title)
        prepared_sections.append(prepare_section(title, module))
        print(f"Processed operators '{title}'")

    nl = "\n"
    outp = f"""
List of operators
===================

This document is automatically generated, and contains the operators that Janis
provides. They are split up by section ({", ".join(section_titles)}) with
the relevant Python import.

For more information about expressions and operators, visit `Expressions in Janis <https://janis.readthedocs.io/en/latest/references/expressions.html>`_.

{nl.join(prepared_sections)}

*This page was autogenerated.*
"""

    with open(listoperators_path, "w+") as f:
        f.write(outp)


def prepare_section(title, module):
    prepared_operators = []

    importstatement = None

    for t, T in vars(module).items():
        if isabstract(T):
            continue
        if not isclass(T):
            continue
        if not issubclass(T, Operator):
            continue

        rettype = T.friendly_signature()

        if importstatement is None:
            importstatement = f"from {T.__module__} import *"

        prepared_operators.append(
            f"""
- **{t}**: ``{rettype}``

{T.__doc__ or ""}
"""
        )

    prepped = "\n\n".join(prepared_operators)
    return f"""
{title}
{len(title) * "+"}

Import with: ``{importstatement}``

{module.__doc__ or ""}


{prepped}
"""


if __name__ == "__main__":
    prepare_operators()
